<?php
namespace data\extend;
/**
 * 央采接口
 *
 * @author pcy
 */
class YangCai 
{
    const CLIENT_ID = 'edee2ae739984b6e91061cae2fe436fc';
    
    const CLIENT_SECRET = 'Ni6l9W6bKAbhA7gMQAsj7FyZ8depEeMM';
    
    const OAUTH_URI = 'http://121.43.184.110:8080/';//测试
    
    const USER_URI = 'http://121.43.184.110:8088/';//测试
    
    const ORDER_URI = 'http://121.43.184.110:8825/';
    
//    const OAUTH_URI = 'http://oauth.zycg.gov.cn/';//正式
//    
//    const USER_URI = 'http://ucenter.zycg.gov.cn/';//正式
    
//    const ORDER_URI = 'http://mall-api.zycg.gov.cn/'; //正式
    
    const USERNAME = 'mall_zyx';
    
    const PASSWORD = 'bvvpnht5zudxb3xa';
    
    const REDIRECT_URI = 'http://t1.phph5.com/receivecode';
    
    
    public static function goToAuth()
    {
        $url = self::OAUTH_URI . 'oauth/authorize';
        
        $params = array
        (
            'response_type' => 'code',
            'scope'         => 'read',
            'client_id'     => self::CLIENT_ID,
            'redirect_uri'  => self::REDIRECT_URI,
//            'state'         => '',
            'type'          => 'cgr'
        );
        
        $paramStr = self::_getParamStr($params);
        
        header("Location:{$url}?{$paramStr}");
    }
    
    public static function logoutUrl()
    {
        return self::OAUTH_URI . 'logout.do';
    }
    
    public static function getAccessToken( $code )
    {
        $url = self::OAUTH_URI . 'oauth/token';
        
        $params = array
        (
            'type'          => 'cgr',
            'grant_type'    => 'authorization_code',
            'client_id'     => self::CLIENT_ID,
            'client_secret' => self::CLIENT_SECRET,
            'code'          => $code,
            'redirect_uri'  => self::REDIRECT_URI
        );
        
        $rs = self::request($url, $params, 'POST');
        
        return isset($rs['access_token']) ? $rs['access_token'] : '';
    }
    
    public static function getUserInfo( $accessToken )
    {
        $url = self::USER_URI . 'admin/admin/product/its/getUserInfo';
        
        $params = array
        (
            'access_token' => $accessToken
        );
        
        return self::request($url, $params, 'POST');
    }
    
    public static function getUnitInfo( $accessToken )
    {
        $url = self::USER_URI . 'admin/admin/product/its/getUnitInfo';
        
        $params = array
        (
            'access_token' => $accessToken
        );
        
        return self::request($url, $params, 'POST');
    }
    
    public static function pushOrder( $orderInfo )
    {
        $url = self::ORDER_URI . 'api/order_create';

        $data = array(
            'user' => array(
                'username' => self::USERNAME,
                'code' => self::_createCode()
            ),
            'param' => $orderInfo
        );
        
        return self::request($url, $data, 'POST', 1);
    }
    
    public static function updateOrder( $orderInfo )
    {
        $url = self::ORDER_URI . 'api/order_update';
        
        $data = array(
            'user' => array(
                'username' => self::USERNAME,
                'code' => self::_createCode()
            ),
            'param' => $orderInfo
        );
        
        return self::request($url, $data, 'POST', 1);
    }
    
    public static function orderLogistics( $logistics )
    {
        $url = self::ORDER_URI . 'api/order_logistics';
        
        $data = array(
            'user' => array(
                'username' => self::USERNAME,
                'code' => self::_createCode()
            ),
            'param' => $logistics
        );
        
        return self::request($url, $data, 'POST', 1);
    }

    private static function _createCode()
    {
        $password = self::PASSWORD;//采购中心进行分配的密码
        $time = date("YmdHi00",time());//要求的时间戳格式
        $str = $password.$time;//拼接成报文
        $dirname = dirname(__FILE__);
        $private_content=file_get_contents($dirname.'/yc_key/rsa_private_zyx.pem');
        $private_key=openssl_get_privatekey($private_content);//加载私钥
        openssl_sign($str,$sign,$private_key, OPENSSL_ALGO_MD5);//对报文签名，结果存于$sign
        openssl_free_key($private_key);//释放空间
        $code=base64_encode($sign);//最终的签名后得到的code
        return $code;
    }
    
    private static function _getParamStr( $params )
    {
        $paramArr = array();
        
        foreach ( $params AS $name => $value )
        {
            $paramArr[] = "$name=$value";
        }
        
        return implode('&', $paramArr);
    }
    
    public static function request($url,$params=array(),$method='GET', $headerId=0)
    {
        $ch = curl_init();
        
        if ( ( $method == 'GET' ) && !empty( $params ) )
        {
            $paramStr = self::_getParamStr($params);
            
            $url .= '?'.$paramStr;
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        if ( $method == 'POST' )
        {
            $headers = array
            (
                0 => array('content-type:application/x-www-form-urlencoded'),
                1 => array('content-type:application/json')
            );
            
            if ( $headerId == 0 )
            {
                $data = self::_getParamStr($params);
            }
            else if ( $headerId == 1 )
            {
                $data = json_encode($params);
            }
            else
            {
                $data = $params;
            }

            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers[$headerId]);
            
            curl_setopt($ch, CURLOPT_POST, 1);
            
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        $result = curl_exec($ch);

        curl_close($ch);

        return json_decode($result, true);
    }
}